import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token:getToken(),
  userInfo:{},
  title:'首页',
  leftIconIsShow:false
}

const mutations = {
  SET_TOKEN:(state,token)=>{
    state.token = token
  },
  SET_USERINFO:(state,info)=>{
    state.userInfo = info
  }
}

const actions = {

  login({commit},data){//用户登陆
    const {username,password} = data
    return new Promise((resolve,reject)=>{
      login({username:username.trim(),password:password.trim()}).then(res=>{
        const {data} = res
        commit('SET_TOKEN',data.token)
        setToken(data.token)
        resolve()
      }).catch(err=>{
        reject(err)
      })
    })
  },

  getInfo({commit}){//获取个人信息
    return new Promise((resolve,reject)=>{
      getUserInfo().then(res=>{
        const {data} = res;
        commit('SET_USERINFO',data)
        resolve(data)
      }).catch(err=>{
        reject(err)
      })
    })
  },

  logOut({commit}){//用户退出
    return new Promise((resolve,reject)=>{
      logout().then(()=>{
        commit('SET_TOKEN','')
        commit('SET_USERINFO',{})
        removeToken()
        location.reload()
        resolve()
      }).catch(err=>{
        reject(err)
      })
    })
  },

  resetToken({commit}){//删除token,用户token过期
    new Promise((resolve)=>{
      commit('SET_TOKEN','')
      commit('SET_USERINFO',{})
      removeToken()
      resolve()
    })
  }

}
export default{
  namespaced: true,
  state,
  mutations,
  actions
}